﻿using MiniFox.Components.Configurations;

namespace MiniFox.Components
{
    /// <summary>
    /// 
    /// </summary>
    internal class SingletonComponentBuilder : DefaultComponentBuilder
    {
        static readonly object _locker;
        Dictionary<string, object> _componentInstances;
        object _spareComponentInstance;
        static SingletonComponentBuilder()
        {
            _locker = new object();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="componentConfig"></param>
        public SingletonComponentBuilder(IComponentConfig componentConfig)
            : base(componentConfig)
        {
            _componentInstances = new Dictionary<string, object>();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="componentName"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public override object ResolveComponentByName(string componentName, params object[] args)
        {
            componentName = string.IsNullOrWhiteSpace(componentName) ? DefaultProvider : componentName;

            lock (_locker)
            {
                object instance = null;
                if (!string.IsNullOrWhiteSpace(componentName))
                {
                    if (!_componentInstances.Keys.Contains(componentName))
                    {
                        instance = base.ResolveComponentByName(componentName, args);
                        _componentInstances.Add(componentName, instance);
                    }
                    return _componentInstances[componentName];
                }
                else
                {
                    if (this._spareComponentInstance  == null)
                        this._spareComponentInstance = this.ResolveComponentBySpare(args);
                    return this._spareComponentInstance;
                }
            }
        }
    }
}
